package it.univaq.mwt.frontoffice.action;

import it.univaq.mwt.business.GiftService;
import it.univaq.mwt.business.ListService;
import it.univaq.mwt.business.NewsService;
import it.univaq.mwt.business.ServicesService;
import it.univaq.mwt.common.business.GiftServiceFactory;
import it.univaq.mwt.common.business.ListServiceFactory;
import it.univaq.mwt.common.business.NewsServiceFactory;
import it.univaq.mwt.common.business.ServicesServiceFactory;
import it.univaq.mwt.model.entity.Gift;
import it.univaq.mwt.model.entity.Lists;
import it.univaq.mwt.model.entity.News;
import it.univaq.mwt.model.entity.Services;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

public class ManageHomeAction extends MappingDispatchAction {

	public ActionForward show(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		HttpSession session = request.getSession();

		// ottengo la factory relativa ai servizi.
		// visualizzo la lista dei servizi relativi al gruppo d'utenza
		ServicesServiceFactory serviceFactory = ServicesServiceFactory
				.getInstance();
		ServicesService facadeServices = serviceFactory.getServicesService();

		// factory relatva alle news, vogio ottenere una lista di news da
		// mostrare nella home.
		NewsServiceFactory newsFactory = NewsServiceFactory.getInstance();
		NewsService facadeNews = newsFactory.getNewsService();

		GiftServiceFactory giftService = GiftServiceFactory.getInstance();
		GiftService facadeGift = giftService.getGiftService();

		// cerco una lista composta da 3 news.
		int limit = 3;

		List<News> news = facadeNews.getNewsListsmall(limit);

		// ottengo un gift da far apparire in home
		List<Gift> giftList = facadeGift.getList(0, 1);
		Gift gift = null;
		if (giftList.size() != 0) {
			gift = giftList.get(0);
		}

		if (session.getAttribute("id_group") != null) {
			int id_group = Integer.parseInt(session.getAttribute("id_group")
					.toString());

			//mosto i servizi del menu di sin
			Set<Services> service = new HashSet<Services>();
			service = facadeServices.getServices(id_group,1);
			
			//mostro i servizi del menu di dx
			Set<Services> service_dx = new HashSet<Services>();
			service_dx = facadeServices.getServices(id_group,2);

			request.setAttribute("gift", gift);
			request.setAttribute("services", service);
			request.setAttribute("services_dx", service_dx);
			request.setAttribute("listNews", news);
			return mapping.findForward("show_home");
		}
		else return mapping.findForward("login");

	}

}
